<?php
/**
 * 货品Logic
 * Created by PhpStorm.
 * User: sunzexin
 * Date: 2017/12/29
 * Time: 18:21
 */

namespace App\Http\Logics\MiniProgram;

use App\Goods;
use App\Http\Logics\BaseLogic;
use App\Product;

class ProductLogic extends BaseLogic
{
    public static function getProductDetail($data)
    {
        $product = Product::with(['productContent', 'category', 'tag', 'goods', 'productPhoto', 'cafe', 'partner'])->find($data['product_id']);
        if (empty($product)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        // 加上货品的最高价和最低价
        $max_price = Goods::where('product_id', $product->id)->max('price');
        $min_price = Goods::where('product_id', $product->id)->min('price');
        $product->max_price = $max_price / 100;
        $product->min_price = $min_price / 100;

        return self::response(self::SUCCESS, $product);
    }

    public static function getProductList($data)
    {
        $query = Product::with(['goods', 'productPhoto'])->where(function($query) use ($data){
            if (isset($data['category_id']) && $data['category_id']){
                $query->where('category_id', $data['category_id']);
            }

            if (isset($data['tag_id']) && $data['tag_id']){
                $query->whereHas('tag', function ($query) use ($data){
                    $query->where('tag.id', $data['tag_id']);
                });
            }
            if (isset($data['cafe_id']) && $data['cafe_id']){
                $query->where('cafe_id', $data['cafe_id']);
            }
        })->where('status', $data['status'])->orderBy('created_at', 'desc');
        $product = $data['limit'] ? $query->paginate($data['limit']) : $query->get();
        $product->map(function ($product) {
            $max_price = Goods::where('product_id', $product->id)->max('price');
            $min_price = Goods::where('product_id', $product->id)->min('price');
            $product->max_price = $max_price / 100;
            $product->min_price = $min_price / 100;
            return $product;
        });
        if (empty($product)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        return self::response(self::SUCCESS, $product);
    }

    public static function search($data)
    {
        $query = Product::with(['goods', 'productPhoto'])->where(function ($query) use ($data){
            $query->where('name', 'like', '%' . $data['keyword'] . '%');
        });
        $product = $data['limit'] ? $query->paginate($data['limit']) : $query->get();
        if (empty($product)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        return self::response(self::SUCCESS, $product);
    }
}